/*
 * Copyright (c) 2023FengTaiSEC Corporation.
 * @Description:
 * @Author: 刘宇薇<liuyuwei@fengtaisec.com>
 * @Date: 2023-06-07 16:04:20
 * @LastEditTime: 2023-10-09 15:54:11
 * @LastEditors: 刘宇薇<liuyuwei@fengtaisec.com>
 * @FilePath: \simulation\web\src\view\scenes\flow\service\utils.js
 * @AmendmentRecord:
 */
import eventBus from 'vue3-eventbus';
// 控制连接桩显示/隐藏
export const showPorts = (node, show) => {
  // 增加类型检查和方法存在性检查
  if (!node || typeof node.hasPorts !== 'function') {
    console.warn('showPorts: 传入的节点对象无效或缺少 hasPorts 方法');
    return;
  }
  
  try {
    const hasPorts = node.hasPorts();
    if (hasPorts) {
      const ports = node.getPorts();
      ports.forEach(port => {
        node.setPortProp(
          port.id,
          'attrs/circle/style/visibility',
          show ? 'visible' : 'hidden',
          { change: 'no' },
        );
      });
    }
  } catch (error) {
    console.error('showPorts 执行错误:', error);
  }
};

export const addTools = (node, tool, add) => {
  tool.forEach(el => {
    const hasTool = node.hasTool(el.name, { change: 'no' });
    if (add) {
      if (!hasTool) {
        let para = { ...el };
        if (para.name === 'node-editor') {
          para['args'] = {};
          para['args']['setText'] = val => {
            if(!val.value) {
              val.value = '';
            }

            eventBus.emit('changeText', {
              id: val.cell.id,
              text: val.value,
            });
          };
        }
        return node.addTools(para, { change: 'no' });
      }
      return;
    }
    if (hasTool) {
      return node.removeTool(el.name, { change: 'no' });
    }
  });
};
